/**
 * Created by XiongXiang on 2017/9/15.
 */
var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
/*
*  引入 webpack 及其配置 config
* */
var webpack = require("webpack");
var webpackConfig = require("./webpack.config");

// 更改模板，自动刷新
var devClient = './dev-client';
Object.keys(webpackConfig.entry).forEach(function (name,i){
    var extras = [devClient]
    webpackConfig.entry[name] = extras.concat(webpackConfig.entry[name])
});

// 调用配置,生成 compiler instance
var complier = webpack(webpackConfig);

var hotMiddleware = require("webpack-hot-middleware")(complier);
// 监听html文件改变事件
complier.plugin('compilation',function (compilation) {
    compilation.plugin('html-webpack-plugin-after-emit',function (data,cb){
        // 发布事件 reload ,这个事件会在 dev-client.js中接受到，然后刷新
        hotMiddleware.publish({action:'reload'})
        cb()
    })
})

// 使用webpack-dev-middleware 插件
var devMiddleware = require('webpack-dev-middleware')(complier,{
    publicPath:webpackConfig.output.publicPath,
    stats:{
        colors:true,
        chunks:false
    }
})

// 注册中间件
app.use(devMiddleware);

// 使用静态资源
app.use(express.static(__dirname+'/'))

// 增加热加载中间件
app.use(hotMiddleware);

app.listen(port,function (err){
    if(err){
        throw  err;
    }
    console.log('listenting at http://localhost:'+port+'\n')
})